<?php

namespace app\admin\controller;

use app\comm\func\CommFunc;
use app\comm\func\Consts;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;

/**
 * Class Classroom 班级模块
 * @package app\admin\controller
 */
class Classroom extends Controller
{
    /**
     * @param Request $request 班级列表
     * @return mixed
     */
    public function ClassList(Request $request)
    {
        $result['msg'] = Db::table('classroom')->select();
        $this->assign('class', $result);
        return $this->fetch();
    }

    /**
     * @param Request $request 添加班级
     * @return mixed
     */
    public function ClassAdd(Request $request)
    {
        if ($request->isPost()) {
            CommFunc::emptyVerify($request->post(), ['class_name', 'subject', 'teacher_id']);
            CommFunc::conditionAdd($condition, $request->post(), ['class_name', 'subject', 'teacher_id']);
            Db::table('classroom')
                ->where('class_name', $condition['class_name'])
                ->count() > 0 ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '班级号重复']) : true;
            $condition['class_name'] = trim($condition['class_name']);
            $condition['open_time'] = time();
            $condition['status'] = 2;
            $condition['stage'] = 1;
            Db::startTrans();
            $insertId = Db::table('classroom')->insertGetId($condition);
            if ($insertId > 0) {
                $teacher_class = [];
                $teacher_class['teacher_id'] = $condition['teacher_id'];
                $teacher_class['classroom_id'] = $insertId;
                $teacher_class['begin_time'] = $condition['open_time'];  //添加班级的时候开始时间默认初级,开始时间就是开班时间
                $teacher_class['end_time'] = 0; //刚开班的班级默认结束时间是0
                $teacher_class['stage'] = 1;
                $insertType = Db::table('teacher_class')->insert($teacher_class);
                if ($insertType > 0) {
                    Db::commit();
                    CommFunc::ajaxReturn(Consts::$successful);
                } else {
                    $this->StartTransFailure();
                }
            } else {
                $this->StartTransFailure();
            }
        } else {
            $teacher = Db::table('admin')->where('role_id', 15)->select();
            $this->assign('teacher', $teacher);
            return $this->fetch();
        }
    }

    /**
     * @param Request $request 选择班级
     */
    public function StageChage(Request $request)
    {
        CommFunc::emptyVerify($request->get(), ['stage', 'cid']);
        CommFunc::conditionAdd($condition, $request->get(), ['stage', 'cid']);
        $res = Db::table('classroom')
            ->where('cid', $condition['cid'])
            ->field('stage')
            ->find();
        $student_class = Db::table('student_class')
             ->where('classroom_id',$condition['cid'])->find(); //如果没查到说明没有学生在这个班级,如果没有学生的话,就无法升级
        if (empty($student_class)){
            CommFunc::ajaxReturn(['status' => 2, 'msg' => '无学生']);
        }
        if ($condition['stage'] < $res['stage']) {
            CommFunc::ajaxReturn(['status' => 2, 'msg' => '阶段无法回退']);
        } else {
            CommFunc::ajaxReturn(Consts::$successful);
        }
    }

    /**
     * 选择班级之后选择教师
     * @param Request $request
     * @return mixed
     */
    public function ChooseTeacher(Request $request)
    {
        if ($request->isPost()) {
            /* 获取选择的老师id和班级id */
            CommFunc::emptyVerify($request->param(), ['teacher_id', 'cid']);
            CommFunc::conditionAdd($condition, $request->param(), ['teacher_id', 'cid']);
            /* 第一阶段,查这个班级下面的所有学生,并且将这些学生的老师修改成切换阶段之后的老师 */
            $students = Db::table('student_class')->where('classroom_id', $condition['cid'])->select();
            foreach ($students as $key => $vo) {
                Db::table('student')->where('id', $vo['student_id'])
                    ->data(['teacher' => $condition['teacher_id']])
                    ->update();
            }
            /* 第二阶段,修改teacher_class表的end_time */
            $classroomStage = Db::table('classroom')->where('cid', $condition['cid'])->find();  /*查用户点击的这个班级当前的stage*/
            Db::table('teacher_class')                                                               /* 关于teacher_class表中当前班级、状态的数据进行end_time更新 */
                ->where('classroom_id', $condition['cid'])
                ->where('stage', $classroomStage['stage'])->data(['end_time' => time()])->update();
            /* 第三阶段，处理teacher_class所需参数 */
            $condition['begin_time'] = time();                  /* 处理begin_time */
            $condition['stage'] = $classroomStage['stage'] + 1; /* 处理stage */
            if ($condition['stage'] > 3) {
                $condition['stage'] = 3;
            }
            $condition['classroom_id'] = $condition['cid'];     /* 处理classroom_id */
            $end_time = Db::table('teacher_class')        /* 处理end_time */
                ->where('classroom_id', $condition['classroom_id'])
                ->where('stage', $classroomStage['stage'])->field('end_time')->find();
            $condition['end_time'] = $end_time['end_time'];
            unset($condition['cid']);
            /* 第四阶段，更新classroom表、teacher_class表、score表、everyday表 */
            Db::startTrans();
            $updateClassType = Db::table('classroom')->where('cid', $condition['classroom_id']) /* 班级表升级之后的修改 */
            ->data([
                'stage' => $condition['stage'],
                'teacher_id' => $condition['teacher_id']
            ])->update();
            if ($updateClassType > 0) {
                $insertId = Db::table('teacher_class')->insertGetId($condition);                     /* 更新teacher_class表 */
                $student = Db::table('student')->where('classroom', $condition['classroom_id'])->select();
                $stage = Db::table('classroom')->where('cid', $condition['classroom_id'])->find();
                if ($insertId > 0) {
                    $scoreInsertType = $this->updateScore($student,$condition,$stage);                    /* 更新score表 */
                    if ($scoreInsertType > 0 || !empty($scoreInsertType)) {
                        $everydayType = $this->updateEvery($student,$condition,$stage);                   /* 更新every表 */
                        $everydayType > 0 ? (Db::commit()).(CommFunc::ajaxReturn(Consts::$successful)) : $this->StartTransFailure();
                    } else {
                        CommFunc::is_RollBack();
                    }
                } else {
                    CommFunc::is_RollBack();
                }
            } else {
                CommFunc::is_RollBack();
            }
        } else {
            CommFunc::emptyVerify($request->get(), ['cid']);
            CommFunc::conditionAdd($condition, $request->get(), ['cid']);
            $res['teacher'] = Db::table('admin')->where('role_id', 15)->select();
            $res['cid'] = $condition['cid'];
            $this->assign('teacher', $res);
            return $this->fetch();
        }
    }

    /**
     * 更新成绩表
     * @param $student
     * @param $condition
     * @param $stage
     * @return int|string
     */
    public function updateScore($student,$condition,$stage)
    {
        foreach ($student as $value) {
            $new = [];
            $new['student_id'] = $value['id'];
            $new['examination'] = json_encode(Consts::$sroce);
            $new['classroom'] = $condition['classroom_id'];
            $new['stage'] = $stage['stage'];
            $scoreInsertType = Db::table('score')->insert($new);
        }
        return $scoreInsertType;
    }

    /**
     * 更新日常表
     * @param $student
     * @param $condition
     * @param $stage
     * @return int|string
     */
    public function updateEvery($student,$condition,$stage)
    {
        foreach ($student as $vo) {
            $every = [];
            $every['student_id'] = $vo['id'];
            $every['option'] = '';
            $every['time'] = time();
            $every['classroom'] = $condition['classroom_id'];
            $every['stage'] = $stage['stage'];
            $everydayType = Db::table('everyday')->insert($every);
        }
        return $everydayType;
    }

    /**
     * @param Request $request 任职记录
     * @return mixed
     */
    public function ClassDeil(Request $request)
    {
        CommFunc::emptyVerify($request->get(), ['cid']);
        CommFunc::conditionAdd($condition, $request->get(), ['cid']);
        $res = Db::table('teacher_class')
            ->where('classroom_id', $condition['cid'])
            ->order('stage')
            ->select();
//        dump($res);
//        exit;
        foreach ($res as $key => $value) {
            $result[$key]['stage'] = $value['stage'];
            $name = Db::table('admin')
                ->where('aid', $value['teacher_id'])
                ->where('role_id', 15)
                ->select();
            foreach ($name as $n) {
                $result[$key]['name'] = $n['name'];
            }
            $result[$key]['begin_time'] = date('Y-m-d', $value['begin_time']);
//            $result[$key]['end_time'] =
        }
//        dump($result);
//        exit;
        $this->assign('deil', $result);
        return $this->fetch();
    }

    /**
     * @param Request $request 班级删除
     */
    public function ClassDel(Request $request)
    {
        CommFunc::emptyVerify($request->post(), ['id']);
        CommFunc::conditionAdd($condition, $request->post(), ['id']);
        $result = Db::table('classroom')
            ->where('cid', $condition['id'])
            ->find();
        $result['status'] == 1 ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '该班级尚未结业,无法删除']) : true;
        $deleteType = Db::table('classroom')
            ->where('cid', $condition['id'])
            ->where('status', 2)
            ->delete();
        if ($deleteType > 0) {
            CommFunc::ajaxReturn(CommFunc::ajaxReturn(Consts::$successful));
        } else {
            CommFunc::ajaxReturn(CommFunc::ajaxReturn(Consts::$failure));
        }
    }

    /**
     * @param Request $request 停用启用
     */
    public function ClassLock(Request $request)
    {
        CommFunc::emptyVerify($request->post(), ['id']);
        CommFunc::conditionAdd($condition, $request->post(), ['id']); //获取到班级id
//        dump($condition);exit;
        $result = Db::table('classroom')
            ->where('cid', $condition['id'])
            ->find();
        $result['status'] == 1 ? $data['status'] = 2 : $data['status'] = 1;
        $updateType = Db::table('classroom')
            ->where('cid', $condition['id'])
            ->update($data);
        if ($updateType) {
            CommFunc::ajaxReturn(Consts::$successful);
        } else {
            CommFunc::ajaxReturn(Consts::$failure);
        }
    }
}